package com.xmy.cultivate.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xmy.cultivate.annotaion.RepeatSubmit;
import com.xmy.cultivate.entity.ClassRoom;
import com.xmy.cultivate.entity.CourseType;
import com.xmy.cultivate.entity.Dict;
import com.xmy.cultivate.service.IClassRoomService;
import com.xmy.cultivate.service.ICourseTypeService;
import com.xmy.cultivate.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 教室 前端控制器
 * </p>
 *
 * @author min
 * @since 2022-07-25
 */
@RestController
@RequestMapping("/api/classRoom")
@Scope("prototype")
public class ClassRoomController extends BaseController {
    @Autowired
    IClassRoomService iClassRoomService;

    @Autowired
    IdWorker idWorker;

    @GetMapping()
    public Result findAll(@RequestParam Map reMap,
                          @RequestParam(value = "schoolId", defaultValue = "") String schoolId,
                          @RequestParam(value = "lessonType", defaultValue = "") String lessonType) {
        Integer pageNum = StringUtils.isEmpty((String) reMap.get("pageNum")) ? 1 : Integer.valueOf((String) reMap.get("pageNum"));
        Integer pageSize = StringUtils.isEmpty((String) reMap.get("pageSize")) ? 10 : Integer.valueOf((String) reMap.get("pageSize"));

        String name = (String) reMap.get("name");

        QueryWrapper<ClassRoom> classRoomQueryWrapper = new QueryWrapper<>();
        classRoomQueryWrapper.eq("deleted", 0);
        classRoomQueryWrapper.eq(StringUtils.isNotBlank(lessonType), "lesson_type", lessonType);
        classRoomQueryWrapper.like(StringUtils.isNotBlank(name), "name", name);
        //classRoomQueryWrapper.like(StringUtils.isNotBlank(name),"name",name);
        if (StringUtils.isNotBlank(schoolId)) {
            classRoomQueryWrapper.and(wrapper -> wrapper.eq("school_id", schoolId).or().eq("school_id", 0));
            //classRoomQueryWrapper.eq("school_id",schoolId);
        } else {
            classRoomQueryWrapper.and(wrapper -> wrapper.in("school_id", this.baseSchoolIdList).or().eq("school_id", 0));
            //classRoomQueryWrapper.in("school_id",this.baseSchoolIdList);
        }
        classRoomQueryWrapper.orderByDesc("id");
        IPage<ClassRoom> iPage = new Page<>(pageNum, pageSize);
        iClassRoomService.findAll(iPage, classRoomQueryWrapper);

        //System.out.print(iPage.getRecords());
        return new Result(Code.OK, new PageResult(iPage.getRecords(), iPage.getTotal(), iPage.getPages()));
    }

    @GetMapping("checkClassRoom")
    public Result checkClassRoom(@RequestParam Map<String, String> reMap,
                                 @RequestParam(value = "schoolIdList", defaultValue = "") String[] schoolIdList,
                                 @RequestParam(value = "lessonType", defaultValue = "") String lessonType) {
        Integer pageNum = StringUtils.isEmpty(reMap.get("pageNum")) ? 1 : Integer.valueOf(reMap.get("pageNum"));
        Integer pageSize = StringUtils.isEmpty(reMap.get("pageSize")) ? 1000 : Integer.valueOf(reMap.get("pageSize"));

        String name = reMap.get("name");

        QueryWrapper<ClassRoom> classRoomQueryWrapper = new QueryWrapper<>();
        classRoomQueryWrapper.eq("deleted", 0);
        classRoomQueryWrapper.like(StringUtils.isNotBlank(name), "name", name);
        classRoomQueryWrapper.eq(StringUtils.isNotBlank(lessonType), "lesson_type", lessonType);

        //String status = reMap.get("status");

        if (schoolIdList.length > 0) {
            classRoomQueryWrapper.and(wrapper -> wrapper.in("school_id", schoolIdList).or().eq("school_id", 0));

        } else {
            classRoomQueryWrapper.and(wrapper -> wrapper.in("school_id", this.baseSchoolIdList).or().eq("school_id", 0));

        }

        /*if (StringUtils.isNotBlank(status)){
            classRoomQueryWrapper.eq("status",status);
        }*/
        classRoomQueryWrapper.orderByDesc("id");

        IPage<ClassRoom> iPage = new Page<>(pageNum, pageSize);
        iClassRoomService.findAll(iPage, classRoomQueryWrapper);

        //System.out.print(iPage.getRecords());
        return new Result(Code.OK, new PageResult(iPage.getRecords(), iPage.getTotal(), iPage.getPages()));
    }

    @GetMapping("/checkClassRoomByStatus")
    public Result checkClassRoomByStatus(@RequestParam Map<String, String> reMap,
                                         @RequestParam(value = "schoolIdList", defaultValue = "") String[] schoolIdList,
                                         @RequestParam(value = "lessonType", defaultValue = "") String lessonType,
                                         @RequestParam(value = "timeStart", defaultValue = "") String timeStart,
                                         @RequestParam(value = "timeEnd", defaultValue = "") String timeEnd,
                                         @RequestParam(value = "weekDates", defaultValue = "") String weekDates,
                                         @RequestParam(value = "yearPart", defaultValue = "") String yearPart,
                                         @RequestParam(value = "quarterNum", defaultValue = "") String quarterNum
    ) {
        Integer pageNum = StringUtils.isEmpty(reMap.get("pageNum")) ? 1 : Integer.valueOf(reMap.get("pageNum"));
        Integer pageSize = StringUtils.isEmpty(reMap.get("pageSize")) ? 1000 : Integer.valueOf(reMap.get("pageSize"));

        String name = reMap.get("name");

        QueryWrapper<ClassRoom> classRoomQueryWrapper = new QueryWrapper<>();
        classRoomQueryWrapper.eq("cr.deleted", 0);
        classRoomQueryWrapper.like(StringUtils.isNotBlank(name), "cr.name", name);
        classRoomQueryWrapper.eq(StringUtils.isNotBlank(lessonType), "cr.lesson_type", lessonType);

        StringBuilder schoolIdSb = new StringBuilder();

        if (schoolIdList.length > 0) {
            classRoomQueryWrapper.and(wrapper -> wrapper.in("cr.school_id", schoolIdList).or().eq("cr.school_id", 0));
            for (String schoolId : schoolIdList) {
                schoolIdSb.append(schoolId).append(",");
            }
            schoolIdSb.deleteCharAt(schoolIdSb.length() - 1);
        } else {
            classRoomQueryWrapper.and(wrapper -> wrapper.in("cr.school_id", this.baseSchoolIdList).or().eq("cr.school_id", 0));
            for (Long schoolId : this.baseSchoolIdList) {
                schoolIdSb.append(schoolId).append(",");
            }
        }

        classRoomQueryWrapper.orderByDesc("cr.id");

        IPage<ClassRoom> iPage = new Page<>(pageNum, pageSize);
        iClassRoomService.checkClassRoomByStatus(iPage, classRoomQueryWrapper, String.valueOf(schoolIdSb), yearPart, quarterNum, lessonType, timeStart, timeEnd, weekDates);

        return new Result(Code.OK, new PageResult(iPage.getRecords(), iPage.getTotal(), iPage.getPages()));
    }

    @GetMapping("/{id}")
    public Result findById(@PathVariable(value = "id") Long id) {
        try {
            ClassRoom classRoom = iClassRoomService.getById(id);
            //long ids =  idWorker.nextId();
            //System.out.println(ids);
            return new Result(Code.OK, classRoom);
        } catch (Exception e) {
            return new Result(Code.ERROR, "", e.getMessage());
        }
    }


    @PostMapping()
    public Result save(@RequestBody ClassRoom classRoom) {
        try {
            classRoom.setId(idWorker.nextId());
            //classRoom.setCreatedId(0L);
            classRoom.setCreatedId(0L);

            //classRoom.setCreatedAt(DateUtil.getNowDateTime());

            //System.out.println(classRoom);

            boolean rs = iClassRoomService.save(classRoom);
            return new Result(rs ? Code.OK : Code.ERROR);
        } catch (Exception e) {
            return new Result(Code.ERROR, e.getMessage());
        }
    }

    @PutMapping("/{id}")
    public Result update(@PathVariable(value = "id") Long id, @RequestBody ClassRoom classRoom) {
        try {
            System.out.println(classRoom);
            //classRoom.setUpdatedAt(DateUtil.getNowDateTime());
            boolean rs = iClassRoomService.updateById(classRoom);
            return new Result(rs ? Code.OK : Code.ERROR);
        } catch (Exception e) {
            return new Result(Code.ERROR, e.getMessage());
        }
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable(value = "id") Long id) {
        try {
            System.out.print("id:" + id);
            boolean rs = iClassRoomService.removeById(id);
            return new Result(rs ? Code.OK : Code.ERROR);
        } catch (Exception e) {
            return new Result(Code.ERROR, e.getMessage());
        }
    }
}
